import { defineStore } from "pinia";

import { loginApi, logoutApi, getRsaPublicKeyApi } from "@/api/auth";
import { getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

import { useStorage } from "@vueuse/core";
export const useUserStore = defineStore("user", () => {
  const user: UserInfo = {};
  const rsaPublicKey = ref("");
  const token = useStorage("accessToken", "");

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  const login = async (loginData: LoginData) => {
    const response = await loginApi(loginData);
    token.value = response.data;
    // token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
  };
  // 获取信息(用户昵称、头像、角色集合、权限集合)
  const getUserInfo = async () => {
    const response = await getUserInfoApi();
    const data = response.data;
    console.log(data);
  };
  const getRsaPublicKey = async () => {
    const response = await getRsaPublicKeyApi();
    const data = response.data;
    rsaPublicKey.value = data;
  };

  // user logout
  const logout = async () => {
    const response = await logoutApi();
    const data = response.data;
    console.log(data);
  };

  // remove token
  const resetToken = () => {
    token.value = "";
    resetRouter();
  };
  return {
    token,
    user,
    rsaPublicKey,
    login,
    getUserInfo,
    logout,
    resetToken,
    getRsaPublicKey,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
